package org.ourgrid.worker.business.requester;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.ourgrid.common.interfaces.to.OutgoingHandle;
import org.ourgrid.common.internal.IResponseTO;
import org.ourgrid.common.internal.RequesterIF;
import org.ourgrid.common.internal.response.LoggerResponseTO;
import org.ourgrid.worker.business.controller.FileTransferController;
import org.ourgrid.worker.business.dao.WorkerDAOFactory;
import org.ourgrid.worker.business.messages.WorkerControllerMessages;
import org.ourgrid.worker.request.TransferRejectedRequestTO;

public class TransferRejectedRequester implements RequesterIF<TransferRejectedRequestTO> {

	public List<IResponseTO> execute(TransferRejectedRequestTO request) {
		List<IResponseTO> responses = new ArrayList<IResponseTO>();
		
		OutgoingHandle handle = request.getHandle();
		
		File fileRejected = WorkerDAOFactory.getInstance().getFileTransferDAO().getUploadingFile(handle);
		String senderPublicKey = request.getSenderPublicKey();
		
		if(fileRejected == null) {
			responses.add(new LoggerResponseTO(WorkerControllerMessages.
					getWorkerReceivesAFileTransferRejectedWithUnknownHandleMessage(handle.getId(), senderPublicKey), LoggerResponseTO.WARN));

			return responses;
		}
		
		String filePath = fileRejected.getAbsolutePath();
		
		if(WorkerDAOFactory.getInstance().getWorkerStatusDAO().isFileTransferErrorState()) {
			responses.add(new LoggerResponseTO(WorkerControllerMessages.
					getWorkerWithErrorReceivesAFileTransferRejectedMessage(filePath, handle.getId(), senderPublicKey), LoggerResponseTO.WARN));
			
			return responses;
		}
		
		FileTransferController.getInstance().fileRejected(handle, responses);
		
		return responses;
	}
}
